package com.stars.questions.commonQuestion.publish.controller;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.stars.base.controller.BaseController;
import com.stars.base.entity.Result;
import com.stars.questions.commonQuestion.publish.entity.CommonReply;
import com.stars.questions.commonQuestion.publish.entity.CommonReplyItem;
import com.stars.questions.commonQuestion.publish.service.CommonPublishService;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;

@RestController
@RequestMapping("/common/publish")
public class CommonPublishController extends BaseController {

    private final CommonPublishService commonPublishService;

    public CommonPublishController(CommonPublishService commonPublishService) {
        this.commonPublishService = commonPublishService;
    }

    @GetMapping("/getQuestion")
    public Result getQuestion(String id) {
        return Result.success(commonPublishService.loadQuestion(id));
    }

    @RequestMapping("/save")
    public Result save(@RequestBody CommonReply reply){
        return commonPublishService.saveReply(super.getRequest(),reply);
    }

    @RequestMapping("/loadQuestionListByConfigId")
    public Result loadQuestionListByConfigId(CommonReplyItem commonReplyItem){
        return Result.success(commonPublishService.loadQuestionListByConfigId(commonReplyItem));
    }

    @GetMapping("/export")
    public ResponseEntity<ByteArrayResource> exportData(CommonReplyItem commonReplyItem) throws IOException {

        // 模拟从数据库或其他数据源获取数据
        String[] headers = {"您对自治区整治形式主义为基层减负政策措施的实施成效如何评价？",
                "您对身边的党员干部树立和践行正确政绩观，不搞“政绩工程”“形象工程”“面子工程”，把精力用在服务群众，解决实际问题上的总体情况如何评价？"
        ,"您对党政机关事业单位精简文件会议数量，提升文件质量、会议效率的成效如何评价？"
        ,"您对党政机关事业单位严控面向基层的督查检查数量，优化方式方法的成效如何评价？"
                ,"您对党政机关事业单位解决调研集中扎堆、只调不研、干扰基层正常工作等问题的成效如何评价？"
                ,"您对党政机关事业单位纠治滥用微信群、钉钉群、APP打卡接龙、考核排名等问题的成效如何评价？"
                ,"您对乡村振兴中因地制宜、实事求是，不搞简单“一刀切”，防止“穷折腾”、搞“花架子”的成效如何评价？"
                ,"您对严格规范涉企行政检查，切实为企业减负的成效如何评价？"
                ,"您对纠治基层公务政务活动中过度使用短视频、电子演示文稿等加重基层负担行为的成效如何评价？"
                ,"您对规范社会事务进校园，减轻教师非教育教学任务负担，确保正常教学秩序的成效如何评价？"
                ,"您对清理规范过多过滥、测评体系繁杂的创建示范和达标活动的成效如何评价？"
                ,"您对党政机关事业单位落实健全规范管理制度，严控借调干部的成效如何评价？"
                ,"您对党政机关事业单位清理规范缺乏实效、浪费资金、名不符实、违反规定的节庆、论坛、展会的成效如何评价？"
                ,"您对党政机关事业单位完善考核办法，优化考核体系指标方式，从考“材料”、查“痕迹”转变为考成效、看“潜绩”，使干部将更多精力用到抓落实上的成效如何评价？"
                ,"您对清理村级组织“滥挂牌”问题（指牌子数量多、种类多、形式多、虚名多，增加基层负担、影响服务效率）的成效如何评价？"
                ,"您对纠治基层多头重复填表格、报数据、交材料的成效如何评价？"
                ,"您对规范明晰基层权责事项的实施情况如何评价？"
                ,"您对落实“三个区分开来”，防止问责泛化简单化的实施情况如何评价？"
                ,"您对关爱基层干部，带薪休假等政策措施的实施情况如何评价？"
                ,"您认为形式主义加重基层负担问题严重的领域主要是？"
                ,"您对解决身边的形式主义突出问题，切实减轻基层无谓的负担是否充满信心？"
                ,"您觉得当前身边突出的形式主义做法加重基层负担的问题有哪些？"
                ,"您对下一步整治形式主义为基层减负工作的建议是什么？"
                ,"您所在行政区?"
                ,"您的职业?"
                ,"填写时间"
                ,"所在区域"
        };


        JSONObject object = commonPublishService.loadQuestionListByConfigId(commonReplyItem);

        JSONArray array = object.getJSONArray("list");

        String[][] data = new String[array.size()][];
        for (int i = 0; i < array.size(); i++) {
            JSONObject item = array.getJSONObject(i);
            data[i] = new String[]{
                    item.getString("q1"),
                    item.getString("q2"),
                    item.getString("q3"),
                    item.getString("q4"),
                    item.getString("q5"),
                    item.getString("q6"),
                    item.getString("q7"),
                    item.getString("q8"),
                    item.getString("q9"),
                    item.getString("q10"),
                    item.getString("q11"),
                    item.getString("q12"),
                    item.getString("q13"),
                    item.getString("q14"),
                    item.getString("q15"),
                    item.getString("q16"),
                    item.getString("q17"),
                    item.getString("q18"),
                    item.getString("q19"),
                    item.getString("q20"),
                    item.getString("q21"),
                    item.getString("q22"),
                    item.getString("q23"),
                    item.getString("q24"),
                    item.getString("q25"),
                    item.getString("createDate"),
                    item.getString("location")
            };
        }

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        PrintWriter writer = new PrintWriter(outputStream);

        // 写入 CSV 文件头
        for (int i = 0; i < headers.length; i++) {
            writer.print(headers[i]);
            if (i < headers.length - 1) {
                writer.print(",");
            }
        }
        writer.println();

        // 写入数据
        for (String[] row : data) {
            for (int i = 0; i < row.length; i++) {
                writer.print(row[i]);
                if (i < row.length - 1) {
                    writer.print(",");
                }
            }
            writer.println();
        }

        writer.flush();
        writer.close();

        byte[] content = outputStream.toByteArray();
        ByteArrayResource resource = new ByteArrayResource(content);

        HttpHeaders headersResponse = new HttpHeaders();
        headersResponse.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=data.csv");

        return ResponseEntity.ok()
                .headers(headersResponse)
                .contentLength(content.length)
                .contentType(MediaType.parseMediaType("text/csv"))
                .body(resource);
    }


    @GetMapping("/flushData")
    public void flushData() {
        commonPublishService.flushData();
    }
}
